package com.zerone.aidlstudy;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    private static final String ACTION_BIND_SERVICE = "com.zerone.aidlstudy.MyService";
    private IMyService myService;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //MyService.MyBinder myBinder = (MyService.MyBinder) service;
            //myService = myBinder.getService();
            myService = IMyService.Stub.asInterface(service);
            try {
                myService.registerListener(salaryPaidListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            myService = null;
        }
    };

    private IOnSalaryPaidListener salaryPaidListener = new IOnSalaryPaidListener.Stub() {
        @Override
        public void onSalaryPaid() throws RemoteException {
            if (myService != null) {
                Random random = new Random();
                List<Employee> employees = myService.getEmployee();
                for (Employee employee: employees) {
                    employee.salary += random.nextInt(3000);
                    Log.d("Client", "Employee Salary: "+employee.toString());
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //启动服务
//        Intent intent = new Intent(MainActivity.this, MyService.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setAction("alexy");
//        bindService(intent, connection, BIND_AUTO_CREATE);
//        startService(intent);

        Button button = (Button) findViewById(R.id.test_button);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if (view.getId() == R.id.test_button) {
                    Intent intentService = new Intent(ACTION_BIND_SERVICE);
                    intentService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    MainActivity.this.bindService(intentService, connection, BIND_AUTO_CREATE);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (myService != null) {
            unbindService(connection);
        }
        super.onDestroy();
    }

}
